package com.cy.module.dingtalk.mobility;

import com.cy.config.EnumConst;
import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.Account;
import com.cy.model.Device;
import com.cy.model.EncryptionLog;
import com.cy.model.User;
import com.cy.model.UserRemarkInfo;
import com.cy.module.WebApiController;
import com.cy.sdk.sms.impl.LuosimaoSMS;
import com.cy.utils.SMSKit;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 快捷操作
 */
@ControllerBind(controllerKey = "/clmp/dingtalk/mobility/shortcut")
public class ShortcutController extends WebApiController {

    public void order(){
        forwardAction("/clmp/order");
    }

    public void userRemarkInfo(){
        forwardAction("/clmp/userRemarkInfo");
    }

    /**
     * 查询用户最近操作设备
     */
    public void getDevicesByUser(){
        Long userId = this.getParaToLong("user_id");
        int page = getParaToInt("pageIndex");
        int pageSize = getParaToInt("limit");
        Device device = getModel(Device.class);
        Map<String, String[]> parasMap = getParaMap();
        if (parasMap != null){
            String start;
            if(parasMap.get("start_time") != null){
                start = parasMap.get("start_time")[0];
                if (StringUtils.isNotBlank(start))
                    device.put("start",start);
            }
            String end;
            if (parasMap.get("end_time") != null){
                end = parasMap.get("end_time")[0];
                if (StringUtils.isNotBlank(end))
                    device.put("end",end);
            }
        }
        Page<Device> devicePage = Device.dao.pageDeviceByUser(page, pageSize, device, userId);
        renderBuiPage(devicePage, 200);
    }

    /**
     * 查询操作过该设备的用户
     */
    public void getUsersByDevice(){
        int page = getParaToInt("pageIndex");
        int pageSize = getParaToInt("limit");
        Device device = getModel(Device.class);
        Map<String, String[]> parasMap = getParaMap();
        if (parasMap != null){
            String start;
            if(parasMap.get("start_time") != null){
                start = parasMap.get("start_time")[0];
                if (StringUtils.isNotBlank(start))
                    device.put("start",start);
            }
            String end;
            if (parasMap.get("end_time") != null){
                end = parasMap.get("end_time")[0];
                if (StringUtils.isNotBlank(end))
                    device.put("end",end);
            }
        }
        Page<User> devicePage = User.dao.pageDeviceByUser(page, pageSize, device);
        renderBuiPage(devicePage, 200);
    }

    /**
     * 获取设备操作日志
     */
    public void getLogs(){
        Long userId = this.getParaToLong("userId");
        Long deviceId = this.getParaToLong("deviceId");
        List<EncryptionLog> encryptionLogs = EncryptionLog.dao.findDetailByDeviceAndUser(deviceId, userId);
        renderJson(encryptionLogs);
    }

    /**
     * 重置设备
     */
    public void resetDevice() {
        Long deviceId = getParaToLong("deviceId");
        Long userId = getParaToLong("userId");
        if (deviceId == null) {
            renderFail(EnumConst.RetCode.PARAMETER_IS_INVALID.getValue());
            return;
        }
        Device device = Device.dao.findById(deviceId);
        device.setStatus(2);//状态改为"测试中"
        if (device.update()){
            /*记录备注信息*/
            Account loginAccount = getLoginAccount();
            String remark = loginAccount.getName() +"重置了饮品机"+ device.getNickName() +"。";
            UserRemarkInfo userRemarkInfo = new UserRemarkInfo();
            userRemarkInfo.setAccountId(loginAccount.getAccountId());
            userRemarkInfo.setUserId(userId);
            userRemarkInfo.setCreateTime(new Date());
            userRemarkInfo.setDeviceId(deviceId);
            userRemarkInfo.setRemark(remark);
            userRemarkInfo.save();
            renderSuccess();
        } else {
            renderFail();
        }
    }

    /**
     * 返修设备
     */
    public void repairDevice() {
        Long deviceId = getParaToLong("deviceId");
        Boolean sendMsg = getParaToBoolean("sendMsg");
        String msg = getPara("msg");
        if (deviceId == null || (sendMsg != null && StringUtils.isBlank(msg))) {
            renderFail(EnumConst.RetCode.PARAMETER_IS_INVALID.getValue());
            return;
        }
        Device device = Device.dao.findById(deviceId);
        device.setManageStatus("M00");//状态改为"返修"
        if (device.update()){
            try {
                Account loginAccount = getLoginAccount();
                /*记录备注信息*/
                UserRemarkInfo userRemarkInfo = getModel(UserRemarkInfo.class);
                userRemarkInfo.setAccountId(loginAccount.getAccountId());
                userRemarkInfo.setCreateTime(new Date());
                userRemarkInfo.setDeviceId(deviceId);
                userRemarkInfo.save();

                if (sendMsg != null){
                    /*发送短信通知客户*/
                    User user = userRemarkInfo.getUser();
                    SMSKit.setSmsService(new LuosimaoSMS());
                    SMSKit.sendMessage(user.getMobile(), msg + SMSKit.MSG_SIGNATURE);

                    /*记录发信息备注信息*/
                    UserRemarkInfo newInfo = new UserRemarkInfo();
                    newInfo.setAccountId(loginAccount.getAccountId());
                    newInfo.setUserId(user.getUserId());
                    newInfo.setDeviceId(deviceId);
                    newInfo.setRemark("已发送信息通知客户，内容如下："+ msg);
                    newInfo.setCreateTime(new Date());
                    newInfo.save();
                }
            } catch (Exception e){
                e.printStackTrace();
            }
            renderSuccess();
        } else {
            renderFail();
        }
    }

    /**
     * 发送短信
     */
    public void sendMsg() {
        String mobile = this.getPara("mobile");
        String msg = this.getPara("msg");
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(msg)) {
            renderFail(EnumConst.RetCode.PARAMETER_IS_NULL.getValue());
            return;
        }
        if (User.dao.findByMobile(mobile) == null){
            renderFail(EnumConst.RetCode.USER_NOTEXISTS.getValue());
            return;
        }
        try {
            SMSKit.setSmsService(new LuosimaoSMS());
            SMSKit.sendMessage(mobile, msg + SMSKit.MSG_SIGNATURE);
            renderSuccess();
        } catch (Exception e){
            renderFail();
        }
    }

    @Override
    public void index() {
    }

}
